<script setup>
import { RouterLink, RouterView, routerKey } from 'vue-router'
import { ref, reactive, computed, onMounted } from 'vue';
import { showNotify, showToast } from 'vant';
import { default as http, getImageUrl } from '@/utils/request.js';
import { uploadImage } from '@/utils/api.js'
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute} from 'vue-router'; //路由器
const router = useRouter(); //获取到 router 对象，用于编程式跳转导航
const route = useRoute();
function toHomePage() {
    router.push("/personal");
}
const onClickLeft = () => history.back();

const orderInfo = reactive({
    address: '',
    orderState: '',
    receivingTime: '',//签收时间
    sellerName: '',
    amount: '',
    orderNumber: '',
    orderTime: '',
    details: '',
    goodsName: '',
    orderPrice: '',
    payTime: '',
    phoneNum: '',
    picture: '',
    trackingNumber: '',//物流单号
    price: ''
})
// 获取订单详情
const getOrderInfo = () => {
    http.get('/user/order/ordernumber/' + route.params.orderNumber).then((res) => {
        orderInfo.sellerName = res.data.data.sellerName;
        orderInfo.amount = res.data.data.amount;
        orderInfo.orderNumber = res.data.data.orderNumber;
        orderInfo.details = res.data.data.details;
        orderInfo.goodsName = res.data.data.goodsName;
        orderInfo.orderPrice = res.data.data.orderPrice;
        orderInfo.picture = res.data.data.picture;
        // resolve(); // 当获取待收货列表成功后，返回一个解析成功的Promise  
    }).catch(err => {
        //   reject(err); // 当请求失败时，返回一个请求失败的Promise  
    });

}

const commentAdd = reactive({

    commentImg: '',
    content: '',
    //评分星星设置
    level: '',
    orderNumber: ''

});

// const updateOrderComment = () => {
//     http.put("/user/order/comment/" + route.params.orderNumber)
//         .then((res) => {
//             const { code, message } = res.data;
//             console.log("=========code", code);
//             if (200 === code) {
//                 showNotify({ type: 'success', message: ' 修改成功' });
//             } else {
//                 showNotify({ type: 'danger', message });
//             }
//         }).catch((err) => {
//             console.log('失败：', err);
//         });
// }

//route.params.xxx 获取路径参数
console.log('orderInfo.orderNumber = ', route.params.orderNumber);
// 添加评论
const addComment = () => {
    commentAdd.orderNumber = route.params.orderNumber;
    const comment = commentAdd;
    // 二次确认
    http.post("/comment", comment, { headers: { 'Content-Type': 'application/json' } })
        .then((res) => {
            console.log('!!!!!!!!!!!!!!!!!评论返回值：', res.data);
            const { code, message } = res.data;
            console.log("=========code", code);
            if (200 === code ) {
                showNotify({ type: 'success', message: '评论成功' });
                setTimeout(() => {
                    router.push("/mycomment"); //使用路径导航
                }, 1000);
            } else {
                showNotify({ type: 'danger', message });
                setTimeout(() => {
                    router.push("/mycomment"); //使用路径导航
                }, 1000);
            }
        }).catch((err) => {
            console.log('评论失败：', err);
            ElMessage.error(`失败`);
        });
}


//折叠面板
const activeNames = ref(['1']);


// 监听评分变化
const onChange = (level) => {
    showToast('当前值：' + level); // 使用 .value 获取 ref 对象的当前值  
};

// //文件上传
const toSelectImage = function () {
    uploaderRef.value.chooseFile();
}
const afterRead = (file) => {
    // 此时可以自行将文件上传至服务器
    console.log(file);
    uploadImage(file)
        .then((url) => {
            console.log("上传成功，返回url = ", url)
            commentAdd.commentImg = url;
            goodsUrl.value = url;
        })
        .catch((err) => {
            console.log("失败消息：", err)
        });
};
// //文件预览
// commentAdd.commentImg = ref([
//     // { url: getImageUrl(comment.commentImg) },
//     // Uploader 根据文件后缀来判断是否为图片文件
//     // 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
//     { url: '', isImage: true },
// ]);

const value = ref('');
const onFailed = () => {
    showNotify({ type: 'success', message: '通知内容' });
}
// 获取元素
let element = document.querySelector('van-list');
// 设置滚动条位置
// element.scrollTop;  // 这里的100是滚动条需要滚动的距离（像素）
const btnRegistIsUse = computed(() => !checked.value); //true 禁用，false可用

onMounted(() => {
    getOrderInfo();
    // addComment();

});


</script>


<template>
    <div>

        <van-col span="24" class="nav_bar">
            <van-nav-bar title="我的评价" left-text="返回" :fixed="true" left-arrow @click-left="onClickLeft" />
        </van-col>

        <br>
        <!-- <br> -->
        <van-list scroll-y="true">
            <div style="margin-top: 40px;">
                <!-- <van-cell-group inset>
                文件预览 
                    <van-uploader v-model="commentAdd.commentImg" name="commentImg" :after-read="afterRead" multiple />
                </van-cell-group> -->
                <!-- <van-cell-group inset>
                 文件上传 
                <van-uploader :after-read="afterRead" />
            </van-cell-group> -->
                <van-field v-model="commentAdd.commentImg" name="commentImg">
                    <template #input>
                        <van-uploader :after-read="afterRead" ref="uploaderRef" v-model="picture" name="commentImg" multiple />
                    </template>
                </van-field>

            </div>
            <div class="template">
                <van-form @submit="addComment" @failed="onFailed">
                    <div style="margin-top: 5px; width: 350px;">
                        <van-cell-group inset>
                            <van-field style=" background-color: #EEE0E5;" v-model="commentAdd.content" name="content"
                                rows="4" autosize label="评价" type="textarea" maxlength="1000" placeholder="请输入评价"
                                show-word-limit="true" />
                        </van-cell-group>
                    </div>
                    <div style="width:350px; color: #c8d175; margin-top: 20px; margin-left: 0%;">
                        <van-cell-group inset>
                            <van-card :num=orderInfo.amount :price=orderInfo.orderPrice :desc=orderInfo.details
                                :title=orderInfo.details :thumb="getImageUrl(orderInfo.picture)" size="large">
                                <template #tags>
                                    <van-tag plain type="primary" style="flex-grow: 1; margin-right: 10px;">{{
                                        orderInfo.goodsName
                                    }}</van-tag>
                                </template>

                            </van-card>

                            <van-config-provider :theme-vars="themeVars">
                                <van-collapse v-model="activeNames">
                                    <van-collapse-item title="去评分" name="1">
                                        <van-field name="leval" v-model="commentAdd.level" label="综合评分">
                                            <template #input>
                                                <van-rate v-model="commentAdd.level" name="level" clearable="true"
                                                    @change="onChange(commentAdd.level)" />
                                            </template>
                                        </van-field>
                                    </van-collapse-item>
                                </van-collapse>
                            </van-config-provider>

                            <!-- <div style="margin: 16px">
                                <van-button round block type="primary" native-type="submit">
                                    提交
                                </van-button>
                            </div> -->

                        </van-cell-group>
                        <div style="margin: 16px; width: 300px">
                            <!-- <van-cell style="color:black;"> -->
                            <van-button round block type="primary" native-type="submit">
                                提交
                            </van-button>
                            <!-- </van-cell> -->
                        </div>


                    </div>
                </van-form>
            </div>

        </van-list>
        <RouterView />
    </div>
</template>

<style scoped>
header {
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 9999;
    line-height: 1.5;
    max-height: 100vh;
}


header {
    line-height: 1.5;
    max-height: 100vh;
}


nav {
    width: 100%;
    font-size: 12px;
    text-align: center;
    margin-top: 2rem;
}

nav a.router-link-exact-active {
    color: var(--color-text);
}

nav a.router-link-exact-active:hover {
    background-color: transparent;
}

nav a {
    display: inline-block;
    padding: 0 1rem;
    border-left: 1px solid var(--color-border);
}

nav a:first-of-type {
    border: 0;
}

@media (min-width: 1024px) {
    header {
        display: flex;
        place-items: center;
        padding-right: calc(var(--section-gap) / 2);
    }


    header .wrapper {
        display: flex;
        place-items: flex-start;
        flex-wrap: wrap;
    }

    nav {
        text-align: left;
        margin-left: -1rem;
        font-size: 1rem;
        padding: 1rem 0;
        margin-top: 1rem;
    }
}

.van-field {
    /* 调整每一行边距 */
    padding: 16px 15px;
}

.van-nav-bar {
    color: #d4e09f;
    width: 100%;
}

.full-width-card {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding: 10px;
    /* 根据需要调整 */
}

.nav_bar {
    position: relative;
    top: -32px;
    /* left:-32px;
    right: -32px; */
    margin: 2px -32px
}

.template {
    background-color: #F0F8FF;
}
</style>
